package com.fuershiye.woman.monitor.service.impl;

import com.fuershiye.woman.monitor.beans.DepartmentAndType;
import com.fuershiye.woman.monitor.beans.ViewUserTel;
import com.fuershiye.woman.monitor.model.*;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.ObjectUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private AdminService adminService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private DepartmentTypeService departmentTypeService;
	@Autowired
	private AreaService areaService;

	@Override
	public Department getDepartIdByName(String name) {
		if(StringUtils.isEmpty(name)){
			return null;
		}
		User user = adminService.findByName(name);
		if (user == null) {
			return null;
		}
		List<Role> roles = user.getRoles();
		for (Role role : roles) {
			if (role == null) {
				continue;
			}
			return departmentService.get(role.getDepartment());
		}
		return null;
	}

	@Override
	public List<ViewUserTel> getSameAreaUserByNowUserRoleDepartment() {
		String name = SecurityUtils.getSubject().getPrincipal() + "";
		if(StringUtils.isEmpty(name)){
			return null;
		}
		Department department = getDepartIdByName(name);
		if(department==null || department.getType()==null){
			return null;
		}
		return adminService.getSameAreaUserByAreaid(department.getArea());
	}

	@Override
	public DepartmentAndType getDepartTypeByName() {
		String name = SecurityUtils.getSubject().getPrincipal() + "";
		if(StringUtils.isEmpty(name)){
			return null;
		}
		Department department = getDepartIdByName(name);
		if(department==null || department.getType()==null){
			return null;
		}
		DepartmentAndType departmentAndType = ObjectUtil.addDepartment2DepartmentAndType(null, department);

		DepartmentType departmentType = departmentTypeService.get(department.getType());
		if(departmentType==null || department.getType()==null){
			return null;
		}
		departmentAndType = ObjectUtil.addDepartmentType2DepartmentAndType(departmentAndType, departmentType);
		return departmentAndType;
	}

	@Override
    public User getDByName(String name) {
		return adminService.findByName(name);
	}

	@Override
	public Area getAreaByName() {
		String name = SecurityUtils.getSubject().getPrincipal() + "";
		Department department = getDepartIdByName(name);
		if(department==null||department.getArea()==null){
			return null;
		}
		return areaService.get(department.getArea());
	}

}
